Styling Form Fields Using :focus and :valid in CSS
You can use the :focus and :valid pseudo-classes together to style form fields based on their state. The :focus pseudo-class applies styles when a field is active (clicked or selected), while :valid applies when the field’s input satisfies its validation rules.
:focus targets form fields that are currently active or being edited by the user.
:valid targets fields whose values meet validation criteria, such as matching a pattern or not being empty when required.
You can combine them as input:focus:valid to apply styles only when both conditions are true.
In this example, when the user clicks the input field, it gets a blue border due to :focus. Once a valid email is entered, the border turns green. When both focused and valid, the input background changes to light green.
Use :focus and :valid to give users clear visual feedback on form interactions.
Combine pseudo-classes like :focus:invalid for error highlighting.
Ensure validation rules (like type or pattern) are properly set in HTML.
Maintain accessibility by ensuring color changes have sufficient contrast.
How would you make a text input turn green when it's valid and has focus, and red when it's invalid but focused?
What happens if you forget to add the required attribute to a form field — will :valid still work?
A user reports that our form fields don’t change color when they type — we’re using :valid, but it’s not working. What could be broken?
We added focus styles to our form fields, but now they conflict with our design system’s focus ring. How do you resolve this without losing accessibility?
We have a form with 20+ dynamic fields that validate asynchronously — how do you efficiently style them as valid/invalid without causing layout thrashing or performance issues?
How would you design a reusable form component that supports custom validation states (e.g., 'pending', 'success', 'error') while still leveraging native :valid/:invalid for accessibility?
Our legacy form system uses inline styles and JS for validation feedback — how would you migrate to CSS-based :valid/:focus styling without breaking existing workflows or accessibility audits?
You’re designing a cross-team form component library — how do you enforce consistent validation styling across 50+ products while accommodating different brand guidelines and compliance requirements?